// *******************************************************************************************************
// # エリア
//   ・希望条件
// *******************************************************************************************************

$(function(){
	var isUnderIe6 = uaInfo.isIe && uaInfo.ieVr <= 6,
		isUnderIe7 = uaInfo.isIe && uaInfo.ieVr <= 7;
		isUnderIe8 = uaInfo.isIe && uaInfo.ieVr <= 8;

	/*******************************************************
	 *　この地域で検索ラッパー
	 *******************************************************/
	var appendWrapper = new APMN.AppendWrapper({
		isFixed: true,
		ieVr: !(isUnderIe6)
	});


	/*******************************************************
	 *　賃料
	 *******************************************************/
	function rentSelect(){
		var $list = $('.box_rent'),
			$down = $('.box_rent .mod_select_content').eq(0),
			$up =   $('.box_rent .mod_select_content').eq(1),
			dwVal = parseInt($down.find('select').val()),
			upVal = parseInt($up.find('select').val()),
			isChanging = false;

		$down.on('change', function(e){
			dwVal = parseInt($(this).find('select').val());
			if (isChanging) return;
			check();
		});
		$up.on('change', function(e){
			upVal = parseInt($(this).find('select').val());
			if (isChanging) return;
			check();
		});

		function check(){
			isChanging = true;
			if (dwVal != 0 && upVal != 0 && dwVal > upVal) {
				var _val1 = upVal;
				var _val2 = dwVal;
				dwVal = _val1;
				upVal = _val2;
				$down.find('select').val(_val1);
				$up.find('select').val(_val2);
				$down.find('.custom_selectInner').text(toSelectText(_val1));
				$up.find('.custom_selectInner').text(toSelectText(_val2));
			};
			isChanging = false;
		};
		function toSelectText(str){
			return str * 0.0001 + '万円';
		};
	};


	/*******************************************************
	 *　間取り　人数
	 *******************************************************/
	function madoriSelect(){
		var $box = $('.box_madori'),
			$type = $box.find('.list_btn_type li'),
			$typeBox = $box.find('input[name=room_type]'),
			$room = $box.find('.list_checkbox5 li'),
			$roomBtn = $box.find('.room_over'),
			data = {
				single: ['ワンルーム','1K','1DK','1LDK','2K','2DK'],
				double: ['1LDK','2K','2DK','2LDK','3K','3DK','3LDK'],
				family: ['2LDK','3K','3DK','3LDK','4K','4DK','4LDK','5K以上']
			},
			id = $typeBox.val(),
			isCheck = null;

		$type.each(function(i){
			var _id = $(this).attr('class');
			$(this).on('click', function(e){
				id = _id;
				$typeBox.val(id);
				changeType();
				changeRoom();
				checkUnder();
			});
		});
		$room.each(function(i){
			if (!isUnderIe7) {
				$(this).find('input').on('ifChecked', function(e){
					checkUnder();
				}).on('ifUnchecked', function(e){
					checkUnder();
				});
			} else {
				$(this).find('input').on('click', function(e){
					checkUnder();
				});
			};
		});

		function changeType(){
			$type.each(function(i){
				if ($(this).attr('class') == id) {
					$(this).find('a').addClass('active');
				} else {
					$(this).find('a').removeClass('active');
				};
			});
		};
		function changeRoom(){
			$room.each(function(i){
				var $self = $(this).find('input'),
					_id = $self.val(),
					_on = false,
					_len = data[id].length;
				for (var j = 0; j < _len; j++) {
					if (data[id][j] == _id) {
						_on = true;
						break;
					};
				};
				if (!isUnderIe7) {
					if (_on) {
						$self.iCheck('check');
					} else {
						$self.iCheck('uncheck');
					};
				} else {
					$self.prop('checked', _on);
				};
			});
		};
		function checkUnder(){
			if (isCheck) return;
			var _id = null;
			setTimeout(function(e){
				$room.each(function(i){
					var $self = $(this).find('input');
					if ($self.prop('checked')) {
						_id = $self.val();
						return false;
					};
				});
				if (_id) {
					$roomBtn.find('span').text(_id + 'より大きい間取りはすべて検索');
					$('#madoriGroup').val(_id);					
					$roomBtn.removeClass('mod_btn_disabled');
					if (!isUnderIe7) {
						$roomBtn.find('input').iCheck('enable');
					} else {
						$roomBtn.find('input').prop('disabled', false);
					};
				} else {
					$('#madoriGroup').val('');
					$roomBtn.find('span').text('間取りを選択');
					$roomBtn.addClass('mod_btn_disabled');
					$roomBtn.removeClass('mod_checked');
					if (!isUnderIe7) {
						$roomBtn.find('input').iCheck('uncheck');
						$roomBtn.find('input').iCheck('disable');
					} else {
						$roomBtn.find('input').prop('checked', false);
						$roomBtn.find('input').prop('disabled', true);
					};
				};
				var _w = $roomBtn.find('label').width();
				$roomBtn.css({ marginLeft:158+(315-_w)*0.5 });
				isCheck = null;
			}, 1);
		};

		if ($roomBtn.find('input').prop('checked')) {
			$roomBtn.addClass('mod_checked');
		};
		/*
		if (id=='' || !id) {
			id = 'double';
			$typeBox.val(id);
			changeRoom();
		};
		*/
		changeType();
		checkUnder();
	};


	/*******************************************************
	 *　専有面積
	 *******************************************************/
	function exclusiveSelect(){
		var $list = $('.box_exclusive'),
			$down = $('.box_exclusive .mod_select_content').eq(0),
			$up =   $('.box_exclusive .mod_select_content').eq(1),
			dwVal = parseInt($down.find('select').val()),
			upVal = parseInt($up.find('select').val()),
			isChanging = false;

		$down.on('change', function(e){
			dwVal = parseInt($(this).find('select').val());
			if (isChanging) return;
			check();
		});
		$up.on('change', function(e){
			upVal = parseInt($(this).find('select').val());
			if (isChanging) return;
			check();
		});

		function check(){
			isChanging = true;
			if (dwVal != 0 && upVal != 0 && dwVal > upVal) {
				var _val1 = upVal;
				var _val2 = dwVal;
				dwVal = _val1;
				upVal = _val2;
				$down.find('select').val(_val1);
				$up.find('select').val(_val2);
				$down.find('.custom_selectInner').text(toSelectText(_val1));
				$up.find('.custom_selectInner').text(toSelectText(_val2));
			};
			isChanging = false;
		};
		function toSelectText(str){
			return str + '㎡';
		};
	};

	function submit(action, method, values) {
		//すべてのhiddenフィールドを自動追加
		//$('input[type=hidden]').each(function(index){
		//こだわりだけに変更
		$('#KodawariId').each(function(index){
			var elem = $(this);
			var val = elem.attr("value");

			values.push({name:elem.attr("id"), value:val});
						
		});
		
 	   var form = $('<form/>', {
	        action: action,
	        method: method
	    });
	    $.each(values, function() {
	        form.append($('<input/>', {
	            type: 'hidden',
	            name: this.name,
	            value: this.value
	        }));    
	    });
	    form.appendTo('body').submit();
	}

	$(".mod_btn_all").click(function() {
		
		var items=[];
		var typ = $('input[name="search_type"]').attr("value");
		items.push({name:'search_type',value:typ});

		$('.search_target').each(function(index){			
			items.push({name:'target_'+index, value:$(this).attr("id")});
		});

		//グループ
		if($('#madoriGroupCheck').prop('checked')){
			var firstIndex = -1;
			var firstMadori = $('#madoriGroup').val();
			
			$('input[name^=madori]').each(function(index){
				if($(this).val() == firstMadori){
					firstIndex = index;
				}
				if(firstIndex > -1 && index >= firstIndex){
					if (!isUnderIe8) {
						$(this).iCheck('check');
					}
					else {
						$(this).prop('checked', true);
					}
				}
			});
		}
		
		$('input:checked').each(function(index){
			var elem = $(this);
			var val = elem.attr("value");
			
			if(elem.attr('name') != undefined){
				//よく利用こだわりじゃない
				if(elem.attr('name').indexOf('Rkodawari') < 0){
					if(elem.attr('name').indexOf('madori') == 0){
						val = 'on';
					}
					items.push({name:elem.attr("name"), value:val});
				}			
				else {//よく利用こだわりじゃない
					var vals = val.split('|');
					for(var i = 0 ; i < vals.length ; i++){
						var kodas = vals[i].split('-');
						items.push({name:kodas[0], value:kodas[1]});
					}
				}
			}			
			
		});

		$('select').each(function(index){
			var elem = $(this);
			items.push({name:elem.attr("name"),
				    value:elem.find("option:selected").attr("value")});
		});
		
		//★★★検索する前家賃と間取り条件をCookieに保存する		
		var tinryo1 = $('select[name=tinryo1]').first().val();
		var tinryo2 = $('select[name=tinryo2]').first().val();
		if(tinryo2 == '9999999') tinryo2 = '0'
		var madori = [];
		$('input[name^=madori]:checked').each(function(){
			madori.push($(this).attr('name'));
		});
		
		
		var cons = "tinryo1:" + tinryo1 + "|tinryo2:" + tinryo2 + "|madori:" + madori.join();
		$.cookie.defaults = { path: '/' }; 
		$.cookie('SAVE_CONS', cons);

		submit('/rstobi/rstobi','POST',items);
		//console.dir(items);
		
	});
	
	//こだわり条件チェック
	if($('#KodawariId').val() != ''){
		var kodawari = $('#KodawariId').val(); 
		$('li[name=rkoda]').each(function(){
			var par = $(this);
			par.find('input[name^=Rkodawari]').each(function(){
				var name = $(this).attr('name');
				var checkName = 'Rkodawari' + String(kodawari);			
				if(name == checkName){
					$(this).attr('checked', 'checked');
					par.find('.mod_checkbox').addClass('checked')
				}
			});
		});				
	}

	// init
	rentSelect();
	madoriSelect();
	exclusiveSelect();
});